﻿using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Xml;
using System.Xml.Serialization;
using Common.Logging;
using In.Api.Dto.Notify;
using In.Api.HttpClients;
using Newtonsoft.Json;
using In.Api.Helpers;
using System.Configuration;
using In.Api.Dto.Notify.Notification;

namespace In.Api.Controllers
{
    public class NotifyController : ApiController
    {


        /// <summary>
        /// 接收通知的统一入口 http://127.0.0.1:8004/Notify/Notification
        /// 1.中文字符统一采用utf-8编码。
        /// 2.HTTP提交必须为POST方式
        /// 3.POST的body数据格式如下
        /// <Notification><NotificationType>Halt</NotificationType><NotificationInfo>halt information</NotificationInfo></Notification>
        /// 4.所有输入参数都大小写敏感.
        /// 5.返回结果为纯文本方式,返回信息如下
        /// <?xml version=\"1.0\"?><Result><ResultCode>0</ResultCode><ResultDesc /></Result>
        /// </summary>
        /// <returns></returns>
        /// 
        private static readonly ILog Logger = LogManager.GetLogger(typeof(NotifyController));
        private const string Success = "0";
        private const string Error = "1";
        private const string SuccessMsg = "调用成功";

        private const string NoticeHalt = "halt";
        private const string NoticeReport = "report";
        private const string NoticeRefund = "refund";
        private const string NoticePay = "pay";
        private static readonly HttpClient HttpClient = new HttpClient();
        [HttpPost]
        [Route("Notify/Notification")]
        public HttpResponseMessage Notification()
        {
            var xmldoc = new XmlDocument(); //xml doc
            HttpResponseMessage retMsg;
            string strCode = Error, strMsg = "未知错误";
            var result = new Response4Notification() { ResultCode = strCode, ResultDesc = strMsg };
            string body = this.Request.Content.ReadAsStringAsync().Result;
            try
            {
                string orderId = "";
                if (string.IsNullOrEmpty(body))
                {
                    strMsg = "请求有误";
                }
                xmldoc.LoadXml(body);
                var notification = xmldoc.SelectSingleNode("/notification");
                var notificationType = xmldoc.SelectSingleNode("/notification/notificationType");
                var notificationInfo = xmldoc.SelectSingleNode("/notification/notificationInfo");
                HospWsLogHelper.Notify(notificationType?.InnerText, notificationInfo?.InnerText, "");
                if (notification == null || notificationType == null || notificationInfo == null)
                {
                    strCode = Error;
                    if (notificationInfo == null)
                        strMsg = "错误:根结点Notification为空";
                    else if (notificationType == null)
                        strMsg = "错误:结点NotificationType为空";
                    else
                        strMsg = "错误:结点NotificationInfo为空";
                    result.ResultCode = strCode;
                    result.ResultDesc = strMsg;
                }
                else
                {
                    PayInfo payinfo = new PayInfo();
                    BillInfo billinfo = new BillInfo();
                    switch (notificationType.InnerText.Trim())
                    {
                        //case "1": //停诊通知
                        //    strCode = NotificationService.ValidateHaltInfo(notificationInfo.InnerXml, out strMsg);
                        //    break;
                        case "2": //缴费通知
                            strCode = NotificationService.ValidatePayInfo(notificationInfo.InnerXml, out strMsg, out payinfo);
                            break;
                        case "3": //预约订单变更通知
                            strCode = NotificationService.ValidateApptInfo(notificationInfo.InnerXml, out strMsg, out orderId);
                            break;
                        //case "4": //出报告通知
                        //    strCode = NotificationService.ValidateReportInfo(notificationInfo.InnerXml, out strMsg);
                        //    break;
                        //case "5": //退款申请
                        //    strCode = NotificationService.ValidateRefundInfo(notificationInfo.InnerXml, out strMsg);
                        //    break;
                        case "6": //生成二维码申请
                            strCode = NotificationService.ValidateBillInfo(notificationInfo.InnerXml, out strMsg, out billinfo);
                            break;
                        case "7": //订单状态
                            strCode = NotificationService.ValidateOrderInfo(notificationInfo.InnerXml, out strMsg, out orderId);
                            break;
                        case "8": //退费
                            strCode = NotificationService.ValidateOrderInfo(notificationInfo.InnerXml, out strMsg, out orderId);
                            break;
                        default:
                            strMsg = "消息类型不存在";
                            strCode = Error;
                            break;
                    }

                    if (strCode == Success) //验证成功
                    {
                        var requestNotification = new Request4Notification
                        {
                            NotificationInfo = notificationInfo.InnerXml,
                            NotificationType = notificationType.InnerText
                        };

                        var wxApiAddress = ConfigurationManager.AppSettings["WxNotificationApiBaseAddress"];
                        var alApiAddress = ConfigurationManager.AppSettings["AliNotificationApiBaseAddress"];

                        if (requestNotification.NotificationType.In("2"))
                        {
                            var rcode = Helpers.HospWsLogHelper.GetPayInfo(payinfo);
                            if (rcode != "0")
                            {
                                var res = HttpClient.PostAsJsonAsync(wxApiAddress, requestNotification).Result;
                                res.EnsureSuccessStatusCode();

                                var callbackResponse = res.Content.ReadAsAsync<Response4Notification>().Result;
                                try
                                {
                                    var alires = HttpClient.PostAsJsonAsync(alApiAddress, requestNotification).Result;
                                    alires.EnsureSuccessStatusCode();
                                    var alicallbackResponse = alires.Content.ReadAsAsync<Response4Notification>().Result;
                                }
                                catch (Exception ex)
                                {
                                    Logger.WarnFormat("AliNotificationApiBaseAddress:{0}", ex.ToString());
                                }
                                if (callbackResponse.ResultCode == "0")
                                {
                                    Helpers.HospWsLogHelper.SavePayInfo(payinfo);
                                }
                            }
                            result.ResultCode = Success;
                            result.ResultDesc = "成功";
                            result.ResponseInfo = new Response4NotificationSubResponseInfo();
                        }
                        else if (requestNotification.NotificationType.In( "7"))
                        {
                            if (string.IsNullOrEmpty(orderId))
                            {
                                result.ResultCode = Error;
                                result.ResultDesc = "OrderId不能为空";
                                result.ResponseInfo = new Response4NotificationSubResponseInfo();
                            }
                            if (orderId.Contains("SC"))
                            {
                                var res = HttpClient.PostAsJsonAsync(wxApiAddress, requestNotification).Result;
                                res.EnsureSuccessStatusCode();

                                var callbackResponse = res.Content.ReadAsAsync<Response4Notification>().Result;
                                result.ResultCode = Success;
                                result.ResultDesc = callbackResponse.ResultDesc;
                                result.ResponseInfo = callbackResponse.ResponseInfo;
                            }
                        }
                        else if (requestNotification.NotificationType.In("8"))
                        {
                            if (string.IsNullOrEmpty(orderId))
                            {
                                result.ResultCode = Error;
                                result.ResultDesc = "OrderId不能为空";
                                result.ResponseInfo = new Response4NotificationSubResponseInfo();
                            }
                            if (orderId.Contains("SC"))
                            {
                                var res = HttpClient.PostAsJsonAsync(wxApiAddress, requestNotification).Result;
                                res.EnsureSuccessStatusCode();

                                var callbackResponse = res.Content.ReadAsAsync<Response4Notification>().Result;
                                result.ResultCode = Success;
                                result.ResultDesc = callbackResponse.ResultDesc;
                                result.ResponseInfo = callbackResponse.ResponseInfo;
                            }
                        }
                        else if (requestNotification.NotificationType.In("6"))
                        {
                            var codeurl = "";
                            if (billinfo != null)
                            {
                                codeurl = Helpers.HospWsLogHelper.GetBillInfo(billinfo, out orderId);
                            }
                            if (string.IsNullOrEmpty(codeurl))
                            {
                                var res = HttpClient.PostAsJsonAsync(wxApiAddress, requestNotification).Result;
                                res.EnsureSuccessStatusCode();

                                var callbackResponse = res.Content.ReadAsAsync<Response4Notification>().Result;
                                result.ResultCode = callbackResponse.ResultCode;
                                result.ResultDesc = callbackResponse.ResultDesc;
                                result.ResponseInfo = callbackResponse.ResponseInfo;
                                if (result.ResultCode == "0")
                                    Helpers.HospWsLogHelper.SaveBillInfo(billinfo, callbackResponse.ResponseInfo.CodeUrl, callbackResponse.ResponseInfo.OrderId);
                            }
                            else
                            {
                                result.ResultCode = "0";
                                result.ResultDesc = "成功";
                                result.ResponseInfo = new Response4NotificationSubResponseInfo()
                                {
                                    AliCodeUrl = "",
                                    CodeUrl = codeurl,
                                    OrderId= orderId,
                                    RefundId = "",
                                    RefundTime = ""
                                };
                            }

                        }
                        //else if (requestNotification.NotificationType.In("8"))
                        //{

                        //    var alires = HttpClient.PostAsJsonAsync(alApiAddress, requestNotification).Result;
                        //    alires.EnsureSuccessStatusCode();

                        //    var alicallbackResponse = alires.Content.ReadAsAsync<Response4Notification>().Result;
                        //    result.ResultCode = alicallbackResponse.ResultCode;
                        //    result.ResultDesc = alicallbackResponse.ResultDesc;
                        //    result.ResponseInfo = alicallbackResponse.ResponseInfo;
                        //}
                    }
                    else
                    {
                        result.ResultDesc = strMsg;
                    }
                }
            }
            catch (Exception ex)
            {
                result.ResultCode = Error;
                result.ResultDesc = ex.Message;

            }
            finally//
            {
                retMsg = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(NotificationService.ToXml(result))
                };
            }

            try
            {
                Logger.InfoFormat("[{0}]通知入参{1} 返回 {2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), body, NotificationService.ToXml(result));
            }
            catch (Exception ex2)
            { }
            return retMsg;
        }


        public Response4Notification GetNoticeResponse(string strCode, string strMsg)
        {
            return new Response4Notification { ResultCode = strCode, ResultDesc = strMsg };
        }

    }
}